package com.xyy.yueshijia.api;

import android.content.RestrictionsManager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xyy.yueshijia.App;
import com.xyy.yueshijia.utils.AppCacheInterceptor;
import com.xyy.yueshijia.utils.AppConfig;

import java.io.File;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by lxs on 2017/2/7.
 * <p>
 * retrofit管理器
 */

public class RetrofitManager {
    protected volatile static RetrofitManager singleton;

    private Retrofit mRetrofit;
    private Retrofit sRetrofit;
    private Gson gson;

    private RetrofitManager() {
        initRetrofit();
    }
    //单例
    public static RetrofitManager getSingleton() {
        if (singleton == null) {
            synchronized (RestrictionsManager.class) {
                if (singleton == null) {
                    singleton = new RetrofitManager();
                }
            }
        }
        return singleton;
    }
    //初始化retrofit
    private void initRetrofit() {
        if (mRetrofit == null) {
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(UrlConstants.BASE_URL)
                    .client(getDefaultOkhttp())//客户端
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .build();
        }
        if (sRetrofit == null) {
            sRetrofit = new Retrofit.Builder()
                    .baseUrl(UrlConstants.BASE_URL)
                    .client(getDefaultOkhttp())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .build();
        }
    }
    //开启缓存
    private OkHttpClient getDefaultOkhttp() {
        return new OkHttpClient.Builder()
                .cache(getResponseCache())//开启缓存
                .addInterceptor(new HttpLoggingInterceptor())
                //缓存
                .addNetworkInterceptor(new AppCacheInterceptor())
                .build();
    }
    /**
     * 获取缓存对象
     * Android/data/包名/cache/response
     */
    public Cache getResponseCache() {
        File externalFilesDir = App.getInstance().getExternalFilesDir(AppConfig.RESPONSE_CACHE);

        return new Cache(externalFilesDir,AppConfig.DEFAULT_RESPONSE_CACHE_SIZE);
    }
    private Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()
                .create();
    }
    public IApiService getIApiService(){
        return  mRetrofit.create(IApiService.class);
    }
    public IApiService getIApiStringService(){
        return  sRetrofit.create(IApiService.class);
    }
}
